//
//  BYSearchController.m
//  OCDemo
//
//  Created by zhumuzhi on 2022/2/13.
//

#import "BYSearchController.h"
#import "DBProduct.h"
#import "ProductModel.h"
#import "BYProductListController.h"


@interface BYSearchController ()<UISearchBarDelegate>

@property (nonatomic, strong) UISearchBar *searchBar;

@end

@implementation BYSearchController

#pragma mark - LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 导航标题
    UILabel *navTitle = [[UILabel alloc] init];
    navTitle.text = @"搜索商品";
    self.navigationItem.titleView = navTitle;
    
    [self.view addSubview:self.searchBar];
}


#pragma mark - UISearchBarDelegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    [[DBProduct sharedInstance] LinkDatabaseAndAddToQueue];
    if ([[DBProduct sharedInstance] selectWithProduct_Name:searchBar.text]) {
        NSLog(@"搜索逻辑-跳转至结果");
        
        NSArray *listArray = [ProductModel mj_objectArrayWithKeyValuesArray:[[NSUserDefaults standardUserDefaults] valueForKey:@"ArryProductSearch"] ];
        
        [searchBar resignFirstResponder];
        
        BYProductListController *goodsList = [[BYProductListController alloc] init];
        goodsList.dataList = listArray;
        goodsList.title = [NSString stringWithFormat:@"搜索词：%@", searchBar.text];
        [self.navigationController pushViewController:goodsList animated:YES];
        
    }else {
        [self.view makeToast:@"没有搜索到相关商品，请重新搜索！"];
        self.searchBar.text = @"";
    }
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - LazyGet

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kAutoWithSize(55))];
        _searchBar.backgroundColor = [UIColor whiteColor];
        _searchBar.placeholder = @"商品名称";
        _searchBar.showsCancelButton = YES; //显示取消按钮
        _searchBar.delegate = self;
        [_searchBar becomeFirstResponder];  //一进入就直接进入编辑模式
    }
    return _searchBar;
}






@end
